<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="com.augurit.common.system.web.auth.form.LoginUserForm"%>
<%@page import="java.io.File"%>
<%LoginUserForm form=(LoginUserForm)request.getSession().getAttribute("SES_LOGIN_USER"); %>
<%@ include file="/common/taglibs.jsp"%>
<%@ include file="/wf/public/meta_wf.jsp"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
String dir=request.getSession().getServletContext().getRealPath("")+File.separator+"TEMP";


%>

<!DOCtype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>电子盖章列表</title>
         <!-- dwr libs -->
<script type='text/javascript' src="${ctx}/dwr/engine.js"></script>
<script type='text/javascript' src="${ctx}/dwr/util.js"></script>
<script type='text/javascript' src="${ctx}/dwr/interface/FileUploadCntl.js"></script>

<script src="${ctx}/gzcgwsp/resources/js/prototype.js" type="text/javascript"></script>
<script src="${ctx}/gzcgwsp/resources/js/YwUtil.js" type="text/javascript"></script>
<script src="${ctx}/gzcgwsp/resources/js/YwGrid.js" type="text/javascript"></script>
<script src="${ctx}/resources/js/aos/tool.js" type="text/javascript"></script>

<script type="text/javascript">
var filepath;
var viewStore;
var win;
var contextpath="<%=basePath%>";
var fileSavePath=getPathBySystem();
Ext.onReady(function(){
  Ext.QuickTips.init();
  
  var cm=new Ext.grid.ColumnModel([  
  new Ext.grid.RowNumberer(),
  {header:'文档名称',dataIndex:'fileName',align:'left',width:'100%'}
  ]);
  
  var viewcm=new Ext.grid.ColumnModel([  
  new Ext.grid.RowNumberer(),
  {header:'文档名称',dataIndex:'filename',align:'center',width:230},
  {header:'创建人',dataIndex:'username',align:'center',width:100},
  {header:'创建时间',dataIndex:'uploaddate',align:'center',width:400}]);
  
  var store=new Ext.data.Store({
			proxy:new Ext.data.HttpProxy({url:'${ctx}/yw-dzgz-list!getByYwid.action?ywId=${id}&templateCode=${templateCode}'}),
			reader:new Ext.data.JsonReader({
			},[
			{name:'id'},
			{name:'fileName'},
			{name:'fileCode'},
			{name:'ywId'},
			{name:'path'}
			])
		});

   viewStore=new Ext.data.Store({
			proxy:new Ext.data.HttpProxy({url:'${ctx}/yw-dzgz-list!listByAjid.action?ajid=${id}&templateCode=${templateCode}'}),
			reader:new Ext.data.JsonReader({
			},[
			{name:'id'},
			{name:'ajid'},
			{name:'filename'},
			{name:'filepath'},
			{name:'username'},
			{name:'uploaddate'}
			])
		});

		
  var grid = new Ext.grid.GridPanel({
    title: '待盖章文件列表',
    collapsible:true,
    width:'100%',
    autoHeight:true,
	store:store,
	cm:cm,
	buttonAlign:'left',
	viewConfig: {
        forceFit: true
	},
	buttons:[{text:'盖章',handler:function(){
	var selections=grid.getSelectionModel().getSelections();
	if(selections.length==0)
	{
	alert("请选择一条记录!");
	return;
	}
  	for(var k=0;k<selections.length;k++)
  	{
  		var record=selections[k];
  		filepath=contextpath+record.get('path');
  		var chinesename = record.get('fileName');
  		var filename = filepath.substring(filepath.lastIndexOf("/")+1);
 		TransUpload(filename,chinesename);
  	}
	}}]
    });
    var gridList=new Ext.grid.GridPanel({
		title:'已盖章文件列表',
		width:'100%',
		autoHeight:true,
		store:viewStore,
		cm:viewcm,
		collapsible:true,
		buttonAlign:'left',
		buttons:[{text:'查看已盖章文件',handler:function(){
		  var selections=gridList.getSelectionModel().getSelections();
		  if(selections.length==0)
		  {
		  	alert("请选择一条记录!");
		  	return;
		  }
		  	for(var j=0;j<selections.length;j++)
		  	{
		  		var record=selections[j];
		  		var path=contextpath+record.get('filepath');
		  		PreviewNetCEB(path);
		  	}
		}}]
	});
  
  	var gridView=new Ext.Panel({
		title:'查看盖章文件',
		collapsible:true,
		width:'100%',
		contentEl:'gridView'
	});
	
	
    var viewport = new Ext.Viewport({
    layout:'column',
    items: [grid,gridList,gridView]
  });
  	
  store.load();
  gridList.store.load();
  
  gridList.on('click',function(){

  });
});
//根据操作系统用不同的路径
function getPathBySystem(){
     var path="";
     var ua = navigator.userAgent.toLowerCase();
     if(ua.indexOf("linux")>=0){
        path="/usr/local/temp";
     }else{
        path="C:\\TEMP\\";
     }
    return path;
}

//文件下载
 function download(_v)
 { 
 document.getElementById("downloadURL").src=_v;
 }
//格式转换
function transMaker(DocName, CebName, LogName, IniName){
	var DTracker;
	DTracker = new ActiveXObject("MakerCom.MakerExt.1");
	var nRet;
	var Error;
	//alert("正转换文件，请稍候......");		
	nRet = DTracker.BeginMaker("");
	if (nRet != 0){
		alert(DTracker.GetErrorMessage(nRet));		
		delete DTracker;
		return false;
	}		
    //alert("开始文档格式转换......请稍后!");		
	nRet = DTracker.SingleFileConvert(DocName, CebName, "标准模板", LogName, IniName);	
	if (nRet != 0){
		alert("MakerOcx transfer error!");
		nRet = DTracker.EndMaker();		
		delete DTracker;
		return false;
	}
	nRet = DTracker.EndMaker();
	if (nRet != 0){
		alert("MakerOcx End error!");		
		delete DTracker;
		return false;
	}	
	//alert("格式转换完成！");	
	delete DTracker;
	return true;
}
function TransUpload(result,chinesename){
	MakeWord(result);// 打开word ，把它保存在D盘，相当于下载
	var DocName, CebName, LogName, IniName;
	var DocNameLen;
	var DocNameWONLen;
	var cebtail;

//	DocName = NewDocForm.OriginalFile.value;
 	DocName =fileSavePath+result;
	DocNameLen = DocName.length;
	DocNameWONLen = DocName.lastIndexOf(".") - 1;
	if (DocNameWONLen == -1){
		DocNameWONLen = DocNameLen;
	}else{
		cebtail = DocName.substring(DocNameWONLen+2, DocNameLen);
	}
	if (cebtail.toLowerCase() == "ceb"){
		CebName = DocName;
	}else{
		CebName = DocName.substring(0, DocNameWONLen+1) + ".ceb";
	}
	
	LogName = DocName.substring(0, DocNameWONLen+1) + ".log";
	IniName = DocName.substring(0, DocNameWONLen+1) + ".ini";
	if (DocName != CebName){
		if (!(transMaker(DocName, CebName, LogName, IniName))){// 格式转换
			alert("格式转换失败，请重试！");
			return false;
		}		
	}
	else{
		alert("当前格式为ceb格式！");
	}
	var f=fileSavePath+result.substring(0,result.lastIndexOf("."))+".ceb";
	//alert(f);
	Stamp_onclick(f);//盖章
	//document.getElementById("t1").value=f;
	//callSet(chinesename);//上传
	return true;
}

function init(){
moveTo(-4,-4); 
resizeTo(screen.availWidth+8,screen.availHeight+8);
}
</script>

<script language="vbs">
Function Stamp_onclick(strCEBFileName)    	
	Dim strErrMessage, lRet, objStampClientTool,g_AffixRegisterURL,g_SendPrintURL,UnitName
	g_AffixRegisterURL="http://172.16.253.169/StampServer/interfaces/background/AffixRegister.aspx"
	g_SendPrintURL="http://172.16.253.169/StampServer/extend/interfaces/SendPrint.aspx"
	UnitName=""

	lRet = ""
	strErrMessage = ""
	strCEBFileName = trim(strCEBFileName)

	if  0 = len(trim(strCEBFileName)) then
		Call Alert("请选择CEB文件！", vbExclamation, "请选择CEB文件！")
		Exit Function
	else
		if UCase(Right(Trim(strCEBFileName), 3)) <> "CEB" then
			Call Alert("只能选择CEB格式的文件！", vbExclamation, "只能选择CEB格式的文件！")
			CEBFileName.value = ""
			Exit Function
		end if                  	 	  
	end if

	set objStampClientTool  = CreateObject("StampClientTool.StampTool")

	' 本地可视化盖章	
	lRet = objStampClientTool.LocalSealStamp(strCEBFileName, UnitName, g_AffixRegisterURL, g_SendPrintURL)
	
	if lRet <> 0 then
		strErrMessage = objStampClientTool.GetErrorMessage()
        alert "盖章失败原因:" & strErrMessage
	end if

	Set objStampClientTool = Nothing	
End Function

Sub PreviewCEB(xuwei)
	Dim lRet
	lRet = DCreateGBForm1.ViewLocalCEB(xuwei)
End Sub

Sub PreviewNetCEB(xuwei)
	Dim lRet
	lRet = DCreateGBForm1.ViewNetCEB(xuwei)
End Sub

</script>
</head>

<body onload="init()">
	<div><iframe id="downloadURL" height="0" width="0" src=""></iframe> </div>
	<div id="gridList"></div>
	<div id="gridView">
		<p align="center">
		  <OBJECT width="900" height="600" id=DCreateGBForm1 classid="clsid:898BAE86-7986-4177-B17F-B9D23C53649C" codebase="CEBViewer.cab"></OBJECT>
		</p>
	</div>
	<div id="fileid">
		<input type="text" style="height:10" id="t1" /><input style="height:10" type="file" name="f1" id="f1"/> <br />
	</div>
	<!--  --><div id="yincanid" style=" background-color:#ffffff; width:700px;height:18px;border:0px solid #C1F248; position:absolute;left:0px;top:0px;"></div>
</body>

<SCRIPT LANGUAGE="javascript"> 
 function MakeWord(filename){
		//var openDocObj = new ActiveXObject("SharePoint.OpenDocuments.2"); // 为了兼容Office XP，可以创建“SharePoint.OpenDocuments.1” 
		//openDocObj.ViewDocument("http://192.168.15.253:8888\\gzcgwsp\\printdoc\\rqjyxkz_gdqy\\1309923429718.doc");  
		//openDocObj.EditDocument("http://192.168.15.253:8888\\gzcgwsp\\printdoc\\rqjyxkz_gdqy\\1309923429718.doc");
	try{ 
	
        var WordApp=new ActiveXObject("Word.Application");
        WordApp.Application.Visible=false; 
        WordApp.NormalTemplate.Saved = true;
        var  templatecode="${templateCode}";
        var url=contextpath+"/printdoc/"+templatecode+"/"+filename;
        try{
	        var Doc=WordApp.Documents.Add(url,false);
	        Doc.saveAs(fileSavePath+filename);
	        Doc.Close();
	        WordApp.Quit();
        }catch(e){
        	 alert("文件不存在"); 
        }
	}catch(e){ 
	    alert("无法调用Office对象，请确保您的机器已安装了Office并已将IE安全级别降低！"); 
	}

 }
</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
//简化写法
function $(id){
    return document.getElementById(id);
}
//崋值方法(就是将文本框的值赋值file对象)
function set1(){
    //将text1中的值复制到剪贴板中
    window.clipboardData.setData('text',$('t1').value); 
    //创建Shell(需要添加到信任站点或解除未签名的ActiveX控件的禁用
    var   WshShell=new   ActiveXObject("WScript.Shell"); 
    //拿到焦点
    $('f1').focus();
    //Ctrl + A 操作
    WshShell.sendKeys("^a");
    //Ctrl + V 操作(sendKeys对于中文赋值操作显得无力,所以只能模拟键盘操作)
    WshShell.sendKeys("^v");
    
}

//给当前网页中四个file对象赋值的方法
function set(chinesename){
    //此处不要用循环,有几个就需要写几个setXX方法
    //setTimeout("set1()",3000);
    //setTimeout("upload('"+chinesename+"')",2000);
}
//检查是否赋值成功
function check(){
    //检查每个file对象是否为空 
    if($('f1').value.length > 0){
        //检查原对象的值的赋值对象的值是否相同
        if($('f1').value == $('t1').value){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
//赋值和file对象的检查
function setValues(chinesename){
    if(!check()){
        set(chinesename);
    }
}
//直接调用的赋值方法
function callSet(chinesename){
    //一定要用setInterval,而不能用循环(循环太快,会造成所有的值赋在一个file对象上)
    //setInterval('setValues()',1000);
    setValues(chinesename);    
}

function upload(chinesename){
var attache = dwr.util.getValue('f1');
var uploadName=dwr.util.getValue('f1').value;
if (uploadName == '') { 
     uploadName=$('t1').value;
    //Ext.Msg.alert("提示!","上传失败!");return;
}
var ajid='${id}';
var username='<%=form.getUser().getUserName() %>';
var dotIndex =uploadName.lastIndexOf(".");
if (dotIndex < 0) dotIndex = uploadName.length;
var attacheName = chinesename;
var attacheType = uploadName.substring(dotIndex + 1);
var obj;	
 obj ={
  ajid:ajid,
  username:username,
  filename:attacheName,
  filetype:attacheType
  };	
	
var params=Ext.encode(obj);
FileUploadCntl.uploadDzgz(params, attache, function (result){
       Ext.Msg.alert("提示!","上传成功!");
       viewStore.load();
});
}

</SCRIPT>

</html>
